package com.example.appframework.login.register.verification;

import androidx.lifecycle.ViewModelProviders;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.graphics.Color;
import android.os.Bundle;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.fragment.app.Fragment;
import androidx.navigation.NavController;
import androidx.navigation.Navigation;

import android.os.CountDownTimer;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import com.example.appframework.R;
import com.example.appframework.login.LoginMainActivity;
import com.example.appframework.mysql.DBConnection;
import com.tencentcloudapi.common.Credential;
import com.tencentcloudapi.common.exception.TencentCloudSDKException;
import com.tencentcloudapi.common.profile.ClientProfile;
import com.tencentcloudapi.common.profile.HttpProfile;
import com.tencentcloudapi.sms.v20190711.SmsClient;
import com.tencentcloudapi.sms.v20190711.models.SendSmsRequest;
import com.tencentcloudapi.sms.v20190711.models.SendSmsResponse;

import java.util.Random;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import java.util.regex.PatternSyntaxException;

public class VerificationFragment extends Fragment {

    private VerificationViewModel mViewModel;
    Button buttonRegisterGetCode;
    EditText registerPhone, registerCode;
    ImageView imagePhone;
    TextView logRCode;
    private String sendCode;
    private String username, password, phone_number, F_phone_number;
    private TimeCount time;

    public static VerificationFragment newInstance() {
        return new VerificationFragment();
    }

    @Override
    public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container,
                             @Nullable Bundle savedInstanceState) {
        return inflater.inflate(R.layout.r_verification_fragment, container, false);
    }

    @Override
    public void onActivityCreated(@Nullable Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);
        //mViewModel = ViewModelProviders.of(this).get(VerificationViewModel.class);
        // TODO: Use the ViewModel

        username = getArguments().getString("username");
        password = getArguments().getString("password");

        buttonRegisterGetCode = getView().findViewById(R.id.buttonRegisterGetCode);

        registerPhone = getView().findViewById(R.id.registerPhone);
        registerCode = getView().findViewById(R.id.registerCode);

        imagePhone = getView().findViewById(R.id.imagePhone);

        logRCode = getView().findViewById(R.id.logRCode);

        imagePhone.setVisibility(View.INVISIBLE);
        logRCode.setVisibility(View.INVISIBLE);

        setMyType(getActivity(), 1);

        time = new TimeCount(60000,1000);

        registerPhone.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence charSequence, int i, int i1, int i2) {
                imagePhone.setVisibility(View.VISIBLE);
                phone_number = registerPhone.getText().toString();
                if(TextUtils.isEmpty(phone_number)){
                    imagePhone.setImageResource(R.drawable.ic_baseline_error);
                }
            }

            @Override
            public void onTextChanged(CharSequence charSequence, int i, int i1, int i2) {
                imagePhone.setVisibility(View.VISIBLE);
                phone_number = registerPhone.getText().toString();
                if(TextUtils.isEmpty(phone_number)){
                    imagePhone.setImageResource(R.drawable.ic_baseline_error);
                }
            }

            @Override
            public void afterTextChanged(Editable editable) {
                imagePhone.setVisibility(View.VISIBLE);
                phone_number = registerPhone.getText().toString();
                if(TextUtils.isEmpty(phone_number)){
                    imagePhone.setImageResource(R.drawable.ic_baseline_error);
                }
                else if(!isPhoneLegal(phone_number)){
                    imagePhone.setImageResource(R.drawable.ic_baseline_error);
                }
                else{
                    new Thread(new Runnable() {
                        @Override
                        public void run() {
                            Boolean temp = true;
                            if(DBConnection.check_phone_number(phone_number)){
                                temp = false;
                                Log.i("show", "been used!");
                            }
                            imagePhone.setImageResource(temp ? R.drawable.ic_baseline_right : R.drawable.ic_baseline_error);
                            if(TextUtils.isEmpty(phone_number)){
                                imagePhone.setImageResource(R.drawable.ic_baseline_error);
                            }
                        }
                    }).start();
                }
            }
        });

        buttonRegisterGetCode.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                sendCode = createCode();
                phone_number = registerPhone.getText().toString();
                if(TextUtils.isEmpty(phone_number)) {
                    Log.i("show", "empty!");
                }
                else if(!isPhoneLegal(phone_number)){
                    Log.i("show", "unlegal");
                }
                else {
                    new Thread(new Runnable(){
                        @Override
                        public void run() {
                            if(DBConnection.check_phone_number(phone_number)){
                                Log.i("show", "the number has been bound");
                            }
                            else{
                                F_phone_number = phone_number;
                                time.start();
                                new Thread(new Runnable() {
                                    @SuppressLint("LongLogTag")
                                    @Override
                                    public void run() {
                                        try{

                                            Credential cred = new Credential("AKIDcIm37wZ8OOHk8ICb5SN6XidLuGQKrkbC", "VloZAWgu0ynPmFclfIpHyd6On83A1JFv");

                                            HttpProfile httpProfile = new HttpProfile();
                                            httpProfile.setEndpoint("sms.ap-beijing.tencentcloudapi.com");

                                            ClientProfile clientProfile = new ClientProfile();
                                            clientProfile.setHttpProfile(httpProfile);

                                            SmsClient client = new SmsClient(cred, "", clientProfile);

                                            SendSmsRequest req = new SendSmsRequest();
                                            String[] phoneNumberSet1 = {"+86" + phone_number};
                                            req.setPhoneNumberSet(phoneNumberSet1);


                                            String[] templateParamSet1 = {sendCode, "5"};
                                            req.setTemplateParamSet(templateParamSet1);

                                            req.setTemplateID("861370");
                                            req.setSmsSdkAppid("1400480944");
                                            req.setSign("趣玩口语");

                                            SendSmsResponse resp = client.SendSms(req);

                                            Log.v("SUCCESS",SendSmsResponse.toJsonString(resp));
                                        } catch (TencentCloudSDKException e) {
                                            Log.e("TencentCloudSDKException",e.toString());
                                        }
                                    }
                                }).start();
                            }
                        }
                    }).start();
                }

            }
        });

        getView().findViewById(R.id.buttonRegisterNext2).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                final String inputcode = registerCode.getText().toString();
                if(TextUtils.isEmpty(inputcode)){
                    logRCode.setVisibility(View.VISIBLE);
                    Log.i("show", "Empty");
                }
                else if(!inputcode.equals(sendCode)){
                    logRCode.setVisibility(View.VISIBLE);
                    Log.i("show", "WrongCode");
                }
                else {
                    logRCode.setVisibility(View.INVISIBLE);
                    Log.i("show", "Right");
                    new Thread(new Runnable() {
                        @Override
                        public void run() {
                            if(DBConnection.check_usename(username)){
                                Log.i("show", "been used!");
                            }
                            else{
                                Log.i("show", "adding");
                                DBConnection.add(username, password, F_phone_number, 1);
                                NavController navController = Navigation.findNavController(getActivity(),R.id.fragmentLogin);
                                navController.navigate(R.id.action_verificationFragment_to_completeFragment);
                            }
                        }
                    }).start();

                }
            }
        });


    }

    private class TimeCount extends CountDownTimer {

        public TimeCount(long millisInFuture, long countDownInterval) {
            super(millisInFuture, countDownInterval);
        }

        @SuppressLint("SetTextI18n")
        @Override
        public void onTick(long millisUntilFinished) {
            buttonRegisterGetCode.setClickable(false);
            buttonRegisterGetCode.setText("(" + millisUntilFinished / 1000 + ") 秒后可重新发送");
        }

        @Override
        public void onFinish() {
            buttonRegisterGetCode.setText("重新获取验证码");
            buttonRegisterGetCode.setClickable(true);

        }
    }


    private void setMyType(Activity activity, int t) {
        super.onAttach(activity);
        ((LoginMainActivity) activity).setType(t);
    }

    private Boolean isPhoneLegal(String str) throws PatternSyntaxException {
        String regExp = "^((13[0-9])|(14[5,7,9])|(15[0-3,5-9])|(166)|(17[3,5,6,7,8])" +
                "|(18[0-9])|(19[8,9]))\\d{8}$";
        Pattern p = Pattern.compile(regExp);
        Matcher m = p.matcher(str);
        return m.matches();
    }

    private String createCode(){
        String code = "";
        Random random = new Random();
        for (int i = 0; i < 6; i++) {
            int r = random.nextInt(10); //每次随机出一个数字（0-9）
            code = code + r;  //把每次随机出的数字拼在一起
        }
        return code;
    }

}